package com.leaguefox.test.domain;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.leaguefox.domain.League;
import com.leaguefox.domain.dao.LeagueDao;

@Configurable
@Component
public class LeagueDataOnDemand {

	@Autowired
	private LeagueDao leagueDao; 
	
	private Random rnd = new java.security.SecureRandom();

	private List<League> data;

	public League getNewTransientLeague(int index) {
        com.leaguefox.domain.League obj = new com.leaguefox.domain.League();
        obj.setName("name_" + index);
        return obj;
    }

	public League getSpecificLeague(int index) {
        init();
        if (index < 0) index = 0;
        if (index > (data.size()-1)) index = data.size() - 1;
        League obj = data.get(index);
        return leagueDao.find( obj.getId());
    }

	public League getRandomLeague() {
        init();
        League obj = data.get(rnd.nextInt(data.size()));
        return leagueDao.find(obj.getId());
    }

	public boolean modifyLeague(League obj) {
        return false;
    }

	@Transactional(propagation = Propagation.REQUIRES_NEW)
    public void init() {
        if (data != null) {
            return;
        }
        
        data = leagueDao.findEntries(0, 10);
        if (data == null) throw new IllegalStateException("Find entries implementation for 'League' illegally returned null");
        if (data.size() > 0) {
            return;
        }
        
        data = new java.util.ArrayList<com.leaguefox.domain.League>();
        for (int i = 0; i < 10; i++) {
            League obj = getNewTransientLeague(i);
            leagueDao.persist(obj);
            data.add(obj);
        }
    }
}
